<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.title" placeholder="请输入MAC信息" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-input v-model="listQuery.device_subject" placeholder="请输入项目名称信息" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-select v-model="listQuery.type" placeholder="区域" clearable class="filter-item" style="width: 130px">
        <el-option v-for="item in calendarTypeOptions" :key="item.key" :label="item.display_name" :value="item.key" />
      </el-select>
      <el-select v-model="listQuery.device_state" placeholder="设备状态" clearable class="filter-item" style="width: 130px">
        <el-option v-for="item in calendarDeviceStateOptions" :key="item.key" :label="item.display_name" :value="item.key" />
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        Search
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="$router.push('/device/index')">
        新增
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >

      <el-table-column label="设备MAC" width="250px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.device_mac }}</span>
          <el-tag>{{ row.info_device_type | devicetypeFilter }}{{row.device_num}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="项目名称" min-width="150px">
        <template slot-scope="{row}">
          <span class="link-type" >{{ row.device_subject }}</span>
          <el-tag>{{ row.device_area | typeFilter }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="设备安装时间" >
        <template slot-scope="{row}">
          <el-date-picker v-model="row.device_install_time" type="date" readonly value-format="timestamp" style="width: 100%;" />
        </template>
      </el-table-column>
      <el-table-column label="设备状态" >
        <template slot-scope="{row}">
          <el-tag :type="row.info_device_state | statusFilter">
          <span>{{ row.info_device_state | devicestateFilter }}</span>
          </el-tag>
        </template>
      </el-table-column>
<!--      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">-->
<!--        <template slot-scope="{row,$index}">-->

<!--          <el-button v-if="row.bank==null" type="primary" size="mini" @click="handleBankUpdate(row)">-->
<!--            更新-->
<!--          </el-button>-->

<!--&lt;!&ndash;          <el-button type="primary" size="mini" @click="handleUpdate(row)">&ndash;&gt;-->
<!--&lt;!&ndash;            上传图片&ndash;&gt;-->
<!--&lt;!&ndash;          </el-button>&ndash;&gt;-->

<!--          &lt;!&ndash;          <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleDelete(row,$index)">&ndash;&gt;-->
<!--          &lt;!&ndash;            Delete&ndash;&gt;-->
<!--          &lt;!&ndash;          </el-button>&ndash;&gt;-->
<!--        </template>-->
<!--      </el-table-column>-->

    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisiblebank" :destroy-on-close="true">
      <el-form ref="dataFormbank" :rules="rules" :model="temp" label-position="left" label-width="100px" style="width: 600px; margin-left:150px;">
        <el-form-item label="项目名称" prop="title">
          <el-input :value="temp.value" />
        </el-form-item>
        <el-form-item label="项目合作银行" prop="resource">
          <el-select v-model="temp.bank " placeholder="请选择合作银行">
            <el-option label="农商银行" value="0" />
            <el-option label="邮储银行" value="1" />
            <el-option label="工商银行" value="2" />
            <el-option label="恒丰银行" value="3" />
            <el-option label="兴业银行" value="4" />
            <el-option label="中国银行" value="5" />
            <el-option label="东营银行" value="6" />
          </el-select>
        </el-form-item>
<!--        <el-form-item v-if="temp.install_person ==0" label="安装联系人" prop="person">-->
<!--          <el-input v-model="temp.install_person" style="width: 46%" />-->
<!--        </el-form-item>-->

<!--        <el-form-item v-if="temp.install_phone ==0" label="安装联系人电话" prop="phone">-->
<!--          <el-input v-model="temp.install_phone" style="width: 46%" />-->
<!--        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisiblebank = false">
          返回
        </el-button>
        <el-button type="primary" @click="sbmitBank('dataFormbank')">
          提交
        </el-button>
      </div>
    </el-dialog>
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :destroy-on-close="true">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="100px" style="width: 600px; margin-left:150px;">
        <el-form-item label="项目名称" prop="title">
          <el-input :value="temp.value" />
        </el-form-item>
        <el-form-item label="项目信息" prop="image">
          <el-upload
            ref="upload"
            class="upload-demo"
            multiple
            action="http://8.141.50.32/admin/subject/uploadfile"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            :file-list="fileList"
            :auto-upload="false"
          >
            <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
            <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <!--        <el-form-item label="Imp">-->
        <!--          <el-rate v-model="temp.importance" :colors="['#99A9BF', '#F7BA2A', '#FF9900']" :max="3" style="margin-top:8px;" />-->
        <!--        </el-form-item>-->
        <el-form-item label="备注">
          <el-input v-model="temp.remark" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" placeholder="Please input" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          返回
        </el-button>
        <el-button type="primary" @click="sbmitimgData('dataForm')">
          提交
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">Confirm</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { fetchPv, createArticle, updateArticle } from '@/api/article'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { getDeviceinfo,updatedevicebank } from '@/api/device'
import { submitUploadimage, DelSubject } from '@/api/subject'
import { scrollTo } from '@/utils/scroll-to'

//设备类型
const calendarDeviceTypeOptions=[
  { key: '0', display_name: '注册机' },
  { key: '1', display_name: '柱状考勤机' },
  { key: '2', display_name: '4G平板考勤机' },
  { key: '3', display_name: '测温平板' },
  { key: '4', display_name: '普通平板' },
  { key: '5', display_name: '海思平板' },
  { key: '6', display_name: '老版平板' },
  { key: '7', display_name: '数据卡' },
  { key: '8', display_name: '路由器' },
  { key: '9', display_name: '其他' },
]

// 状态信息
const calendarDeviceStateOptions = [
  { key: '0', display_name: '停用' },
  { key: '1', display_name: '可使用' },
  { key: '2', display_name: '使用中' },
  { key: '3', display_name: '维修中' }
]

// 区域信息
const calendarTypeOptions = [
  { key: '371601', display_name: '市直管' },
  { key: '371602', display_name: '滨城区' },
  { key: '371604', display_name: '开发区' },
  { key: '371605', display_name: '高新区' },
  { key: '371606', display_name: '北海新区' },
  { key: '371621', display_name: '惠民县' },
  { key: '371622', display_name: '阳信县' },
  { key: '371623', display_name: '无棣县' },
  { key: '371624', display_name: '沾化区' },
  { key: '371625', display_name: '博兴县' },
  { key: '371626', display_name: '邹平市' },
  { key: '371627', display_name: '工业园区' }
]
// 状态信息
const calendarStateOptions = [
  { key: '0', display_name: '停工' },
  { key: '1', display_name: '开工' },
  { key: '2', display_name: '完工' },
  { key: '3', display_name: '筹建' },
  { key: '4', display_name: '立项' }
]
// 合作银行信息
const calendarBankOptions = [
  { key: '0', display_name: '农商银行' },
  { key: '1', display_name: '邮储银行' },
  { key: '2', display_name: '工商银行' },
  { key: '3', display_name: '恒丰银行' },
  { key: '4', display_name: '兴业银行' },
  { key: '5', display_name: '中国银行' },
  { key: '6', display_name: '东营银行' }
]

// arr to obj, such as { CN : "China", US : "USA" }
//设备状态
const calendarDeviceStateKeyValue = calendarDeviceStateOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

//获取设备历史信息
const calendarDeviceTypeKeyValue = calendarDeviceTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})
// 获取项目的状态信息
const calendarStateKeyValue = calendarStateOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})
// 获取合作银行的信息
const calendarBankKeyValue = calendarBankOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  inject:['reload'],
  name: 'ComplexTable',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        0: 'error',
        1: 'success',
        3: 'danger',
        2: 'warning'
      }
      return statusMap[status]
    },
    devicestateFilter(type) {
      return calendarDeviceStateKeyValue[type]
    },
    devicetypeFilter(type) {
      return calendarDeviceTypeKeyValue[type]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    },
    stateFilter(type) {
      return calendarStateKeyValue[type]
    },
    bankFilter(type) {
      return calendarBankKeyValue[type]
    }
  },
  data() {
    return {
      // 文件列表
      fileList: [],
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 10,
        importance: undefined,
        value: undefined,
        area: undefined,
        sort: '+id',
        title:'',
        subjecttitle:''
      },
      importanceOptions: [1, 2, 3],
      calendarTypeOptions,
      calendarDeviceStateOptions,
      // sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: ['published', 'draft', 'deleted'],
      calendarStateOptions: [],
      showReviewer: false,
      temp: {
        id: undefined,
        num: '',
        bank: '',
        timestamp: new Date(),
        value: '',
        area: '',
        status: '',
        install_person:'',
        install_phone:''
      },
      image: '',
      dialogFormVisible: false,
      dialogFormVisiblebank: false,
      dialogStatus: '',
      textMap: {
        update: '上传图片信息',
        create: 'Create',
        updatebank:'更新银行信息'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        type: [{ required: true, message: 'type is required', trigger: 'change' }],
        timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
        //title: [{ required: true, message: 'title is required', trigger: 'blur' }],
        bank: [{ required: true, message: 'title is required', trigger: 'blur' }]
        // image:[{ required: true, message: 'image is required', trigger: 'blur' }],

      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 文件上传
    submitUpload() {
      this.$refs.upload.submit()
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
      this.image = ''
      for (const i in fileList) {
        this.image += fileList[i]['response'] + ';'
      }
    },
    handlePreview(file) {
      console.log(file)
    },
    handleSuccess(response, file, fileList) {
      this.image = ''
      for (const i in fileList) {
        this.image += fileList[i]['response'] + ';'
      }
    },

    getList(val) {
      this.listLoading = true
      if (val != undefined) {
        this.page = val.page,
        this.limit = val.limit
      }
      this.type = this.listQuery.type
      this.title = this.listQuery.title
      this.device_state = this.listQuery.device_state
      this.device_subject=this.listQuery.device_subject
      getDeviceinfo(
        {
          page: this.page,
          limit: this.limit,
          device_area: this.type,
          device_mac: this.title,
          device_state:this.device_state,
          device_subject: this.device_subject,
        }).then((res) => {
        if (res.code == '20000') {
          this.list = res.data
          // console.log(this.list)
          this.total = res.msg
          setTimeout(() => {
            this.listLoading = false
          }, 1.5 * 1000)

          // this.$message('提交成功!')
        } else {
          this.$message({
            message: '提交失败，请联系管理员!',
            type: 'error'
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleBankUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'updatebank'
      this.dialogFormVisiblebank = true
      this.$nextTick(() => {
        this.$refs['dataFormbank'].clearValidate()
      })
    },
    sbmitimgData(dataForm) {
      if (this.image.length == 0) {
        this.$notify({
          title: '信息',
          message: '请选择照片后再提交',
          type: 'warning',
          duration: 2000
        })
        return false
      }
      this.$refs['dataForm'].validate((valid) => {
        const tempData = Object.assign({}, this.temp)

        // 获取上传的文件列表
        if (valid) {
          submitUploadimage(
            {
              subject_image: this.image,
              subject_num: tempData.num,
              subject_remark: tempData.remark
            }).then((res) => {
            if (res.code == '20000') {
              // console.log(this.list)
              setTimeout(() => {
                this.listLoading = false
              }, 1.5 * 1000)
              if (res.data == 0) {
                this.$notify({
                  title: '信息',
                  message: '数据相同，无需重复提交',
                  type: 'warning',
                  duration: 2000
                })
              } else {
                this.$notify({
                  title: '信息',
                  message: '提交成功',
                  type: 'success',
                  duration: 2000
                })
                console.log('b')
                this.dialogFormVisible = false
                console.log('e')
              }
            } else {
              this.$message({
                message: '提交失败，请联系管理员!',
                type: 'error'
              })
            }
          }).catch(err => {
            console.log('err', err)
          })
        }
      })
    },

    sbmitBank(dataFormbank) {
      this.$refs['dataFormbank'].validate((valid) => {
        const tempData = Object.assign({}, this.temp)
        console.log(tempData)
        // 获取上传的文件列表
        if (valid) {
          updatedevicebank(
            {
              subject_num: tempData.num,
              bank:tempData.bank
            }).then((res) => {
            if (res.code == '20000') {
              // console.log(this.list)
              setTimeout(() => {
                this.listLoading = false
              }, 1.5 * 1000)
              if (res.data == 0) {
                this.$notify({
                  title: '信息',
                  message: '数据相同，无需重复提交',
                  type: 'warning',
                  duration: 2000
                })
              } else {
                this.$notify({
                  title: '信息',
                  message: '提交成功',
                  type: 'success',
                  duration: 2000
                })
                this.reload()
                console.log('b')
                this.dialogFormVisiblebank = false
                console.log('e')
              }
            } else {
              this.$message({
                message: '提交失败，请联系管理员!',
                type: 'error'
              })
            }
          }).catch(err => {
            console.log('err', err)
          })
        }
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },

    resetTemp() {
      this.temp = {
        id: undefined,
        importance: 1,
        remark: '',
        timestamp: new Date(),
        title: '',
        status: '',
        type: ''
      }
    },

    handleDelete(row, index) {
      console.log(row.num, index)
      DelSubject(
        {
          subject_num: row.num
        }).then((res) => {
        if (res.code == '20000') {
          // console.log(this.list)
          setTimeout(() => {
            this.listLoading = false
          }, 1.5 * 1000)

          //  this.$message('修改成功!')
          if (res.data == 0) {
            this.$notify({
              title: '信息',
              message: '已删除，无需重复操作',
              type: 'warning',
              duration: 2000
            })
          } else {
            this.$notify({
              title: '信息',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
          }
        } else {
          this.$message({
            message: '删除失败，请联系管理员史岩松!',
            type: 'error'
          })
        }
      })
      this.list.splice(index, 1)
    },
    handleFetchPv(pv) {
      fetchPv(pv).then(response => {
        this.pvData = response.data.pvData
        this.dialogPvVisible = true
      })
    }

  }
}
</script>
